package com.iotechn.unimall.app.api.inspection;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dobbinsoft.fw.core.exception.AdminServiceException;
import com.dobbinsoft.fw.core.exception.ServiceException;
import com.dobbinsoft.fw.support.model.Page;
import com.iotechn.unimall.data.domain.ComputerRoomDO;
import com.iotechn.unimall.data.domain.EquipmentDO;
import com.iotechn.unimall.data.domain.InspectionDO;
import com.iotechn.unimall.data.dto.InspectionDTO;
import com.iotechn.unimall.data.enums.ComputerRoomStatusType;
import com.iotechn.unimall.data.enums.EquipmentStatusType;
import com.iotechn.unimall.data.enums.InspectionStatusType;
import com.iotechn.unimall.data.exception.ExceptionDefinition;
import com.iotechn.unimall.data.mapper.ComputerRoomMapper;
import com.iotechn.unimall.data.mapper.EquipmentMapper;
import com.iotechn.unimall.data.mapper.InspectionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;


/**
 * Generate Code By Unimall
 */
@Service
public class AppInspectionServiceImpl implements AppInspectionService {

    @Autowired
    private InspectionMapper inspectionMapper;
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private ComputerRoomMapper computerRoomMapper;

    @Override
    public boolean delete(Long id, Long adminId) throws ServiceException {
        return inspectionMapper.deleteById(id) > 0;
    }

    @Override
    public Page<InspectionDO> list(Long roundsId, Integer page, Integer limit) throws ServiceException {
        QueryWrapper<InspectionDO> wrapper = new QueryWrapper<InspectionDO>();
        if (roundsId != null) {
            wrapper.eq("rounds_id", roundsId);
        }
        return inspectionMapper.selectPage(Page.div(page, limit, InspectionDO.class), wrapper.orderByAsc("room_name","equipment_type"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(String str) throws ServiceException {
        Date now = new Date();
        Integer num = 3;
        List<InspectionDO> inspectionDOS = JSONArray.parseArray(str).toJavaList(InspectionDO.class);
        if (!CollectionUtils.isEmpty(inspectionDOS)){
            for (InspectionDO inspectionDO1 : inspectionDOS){
                InspectionDO insertDO = new InspectionDO();
                insertDO.setRoundsId(inspectionDO1.getRoundsId());
                insertDO.setRoomName(inspectionDO1.getRoomName());
                insertDO.setRoomId(inspectionDO1.getRoomId());
                insertDO.setEquipmentType(inspectionDO1.getEquipmentType());
                insertDO.setEquipmentNo(inspectionDO1.getEquipmentNo());
                insertDO.setEquipmentId(inspectionDO1.getEquipmentId());
                insertDO.setRunningStatus(inspectionDO1.getRunningStatus());
                //有温度
                if(inspectionDO1.getTemperature() != null){
                    insertDO.setTemperature(inspectionDO1.getTemperature());
                    //巡检结果，异常
                    if (insertDO.getTemperature()>24 || insertDO.getRunningStatus()==2 ){
                        insertDO.setInspectionStatus(InspectionStatusType.inspection_abnormal.getCode());
                        //温度异常
                        if (insertDO.getTemperature()>24 && insertDO.getRunningStatus()==1 ){
                            insertDO.setAbnormalMatters("温度"+ insertDO.getTemperature() + "℃");
                        }
                        //温度状态都异常
                        else if(insertDO.getTemperature()>24 && insertDO.getRunningStatus()==2 ){
                            insertDO.setAbnormalMatters("温度"+ insertDO.getTemperature() + "℃、" + "运行异常");
                        }
                        //状态异常
                        else if(insertDO.getTemperature()<=24 && insertDO.getRunningStatus()==2 ){
                            insertDO.setAbnormalMatters("运行异常");
                        }
                        insertDO.setAbnormalStatus(InspectionStatusType.abnormal_nohandle.getCode());
                        //查询设备
                        EquipmentDO equipmentDO = equipmentMapper.selectById(insertDO.getEquipmentId());
                        equipmentDO.setStatus(EquipmentStatusType.abnormal.getCode());
                        equipmentMapper.updateById(equipmentDO);
                        //查询机房
                        ComputerRoomDO computerRoomDO = computerRoomMapper.selectById(insertDO.getRoomId());
                        if (!"异常".equals(computerRoomDO.getStatus()) || num.equals(computerRoomDO.getAppStatus()) ){
                            computerRoomDO.setStatus("异常");
                            computerRoomDO.setAppStatus(ComputerRoomStatusType.abnormal.getCode());
                            computerRoomMapper.updateById(computerRoomDO);
                        }
                    }
                    //正常
                    else {
                        insertDO.setInspectionStatus(InspectionStatusType.inspection_normal.getCode());
                        //查询设备
                        EquipmentDO equipmentDO = equipmentMapper.selectById(insertDO.getEquipmentId());
                        equipmentDO.setStatus(EquipmentStatusType.normal.getCode());
                        equipmentMapper.updateById(equipmentDO);
                        //查询机房
                        ComputerRoomDO computerRoomDO = computerRoomMapper.selectById(insertDO.getRoomId());
                        if (!"异常".equals(computerRoomDO.getStatus()) || num.equals(computerRoomDO.getAppStatus()) ){
                            computerRoomDO.setStatus("正常");
                            computerRoomDO.setAppStatus(ComputerRoomStatusType.normal.getCode());
                            computerRoomMapper.updateById(computerRoomDO);
                        }
                    }
                }
                //没温度
                else {
                    //巡检结果，异常
                    if (insertDO.getRunningStatus()==2 ){
                        insertDO.setInspectionStatus(InspectionStatusType.inspection_abnormal.getCode());
                        insertDO.setAbnormalMatters("运行异常");
                        insertDO.setAbnormalStatus(InspectionStatusType.abnormal_nohandle.getCode());
                        //查询设备
                        EquipmentDO equipmentDO = equipmentMapper.selectById(insertDO.getEquipmentId());
                        equipmentDO.setStatus(EquipmentStatusType.abnormal.getCode());
                        equipmentMapper.updateById(equipmentDO);
                        //查询机房
                        ComputerRoomDO computerRoomDO = computerRoomMapper.selectById(insertDO.getRoomId());
                        if (!"异常".equals(computerRoomDO.getStatus()) || num.equals(computerRoomDO.getAppStatus()) ){
                            computerRoomDO.setStatus("异常");
                            computerRoomDO.setAppStatus(ComputerRoomStatusType.abnormal.getCode());
                            computerRoomMapper.updateById(computerRoomDO);
                        }
                    }
                    //正常
                    else if (insertDO.getRunningStatus()==1 ) {
                        insertDO.setInspectionStatus(InspectionStatusType.inspection_normal.getCode());
                        //查询设备
                        EquipmentDO equipmentDO = equipmentMapper.selectById(insertDO.getEquipmentId());
                        equipmentDO.setStatus(EquipmentStatusType.normal.getCode());
                        equipmentMapper.updateById(equipmentDO);
                        //查询机房
                        ComputerRoomDO computerRoomDO = computerRoomMapper.selectById(insertDO.getRoomId());
                        if (!"异常".equals(computerRoomDO.getStatus()) || num.equals(computerRoomDO.getAppStatus()) ){
                            computerRoomDO.setStatus("正常");
                            computerRoomDO.setAppStatus(ComputerRoomStatusType.normal.getCode());
                            computerRoomMapper.updateById(computerRoomDO);
                        }
                    }
                }
                if (inspectionDO1.getHumidity() != null){
                    insertDO.setHumidity(inspectionDO1.getHumidity());
                }
                if (inspectionDO1.getRunningStatus() != null){
                    insertDO.setRunningStatus(inspectionDO1.getRunningStatus());
                }
                insertDO.setPhoto(inspectionDO1.getPhoto());
                if (inspectionDO1.getTemperature()==null && inspectionDO1.getHumidity()== null && inspectionDO1.getRunningStatus()== null){
                    insertDO.setInspectionStatus(InspectionStatusType.inspection_missed.getCode());
                }
                insertDO.setGmtUpdate(now);
                insertDO.setGmtCreate(now);
                inspectionMapper.insert(insertDO);
            }
        }
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String edit(Long id, String roomName, Long roomId, String equipmentType, String equipmentNo, Long equipmentId, Integer runningStatus, String photo, Integer inspectionPeople, Integer rounds, Long adminId) throws ServiceException {
        Date now = new Date();
        InspectionDO updateDO = new InspectionDO();
        updateDO.setId(id);
        updateDO.setRoomName(roomName);
        updateDO.setRoomId(roomId);
        updateDO.setEquipmentType(equipmentType);
        updateDO.setEquipmentNo(equipmentNo);
        updateDO.setEquipmentId(equipmentId);
        updateDO.setRunningStatus(runningStatus);
        updateDO.setPhoto(photo);
        updateDO.setGmtUpdate(now);
        if (inspectionMapper.updateById(updateDO) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    /**
     * 设备记录
     *
     * @return
     * @throws ServiceException
     */
    @Override
    public Page<InspectionDTO> recordList(Long equipmentId, String startDate, String endDate, Integer page, Integer limit, Long adminId) throws ServiceException {
        Page<InspectionDTO> pages = inspectionMapper.getRecordList(Page.div(page, limit, InspectionDTO.class), equipmentId, startDate, endDate);
        return pages;
    }

    /**
     * 异常处理列表
     *
     * @return
     * @throws ServiceException
     */
    @Override
    public Page<InspectionDTO> exceptionHandlingList(String searchKeyWord, String searchType, String room, Integer page, Integer limit, Long adminId) throws ServiceException {
        Page<InspectionDTO> pages = inspectionMapper.getExceptionList(Page.div(page, limit, InspectionDTO.class), searchKeyWord, searchType, room);
        return pages;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String remark(Long id, String remarks, Long adminId) throws ServiceException {
        Date now = new Date();
        InspectionDO inspectionDO = inspectionMapper.selectById(id);
        inspectionDO.setRemarks(remarks);
        inspectionDO.setGmtUpdate(now);
        if (inspectionMapper.updateById(inspectionDO) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String exceptionHandling(Long id, Long adminId) throws ServiceException {
        Date now = new Date();
        InspectionDO inspectionDO = inspectionMapper.selectById(id);
        inspectionDO.setAbnormalStatus(InspectionStatusType.abnormal_handle.getCode());
        inspectionDO.setGmtUpdate(now);
        //查询某个设备所有未处理的巡检
        List<InspectionDO> inspectionDOS = inspectionMapper.selectList(new QueryWrapper<InspectionDO>()
        .eq("equipment_id",inspectionDO.getEquipmentId()).eq("abnormal_status",6).eq("inspection_status",4));
        //该设备所有异常都已处理
        if (inspectionDOS.size() ==0 ){
            //查询设备，变成正常
            EquipmentDO equipmentDO = equipmentMapper.selectById(inspectionDO.getEquipmentId());
            equipmentDO.setStatus(EquipmentStatusType.normal.getCode());
            equipmentMapper.updateById(equipmentDO);
        }
        //查询某个机房所有未处理的巡检
        List<InspectionDO> inspectionDOS1 = inspectionMapper.selectList(new QueryWrapper<InspectionDO>()
                .eq("room_id",inspectionDO.getRoomId()).eq("abnormal_status",6).eq("inspection_status",4));
        //该机房所有异常都已处理
        if (inspectionDOS1.size() ==0 ){
            //查询机房，变成正常
            ComputerRoomDO computerRoomDO = computerRoomMapper.selectById(inspectionDO.getRoomId());
            computerRoomDO.setStatus("正常");
            computerRoomMapper.updateById(computerRoomDO);
        }
        if (inspectionMapper.updateById(inspectionDO) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }
}
